# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2019/1/30
# python-version    : Python 3.7.0
# description       : 获取数据库文章信息

import os
from com.articles.microapp.utils.xml_utils import XMLParser
from com.articles.microapp.utils.db_utils import DbUtils
from com.articles.microapp.entities.article import Article
from com.articles.microapp.utils.cache_utils import Cache
from com.articles.microapp.utils.string_utils import String
from com.articles.microapp.utils.logger_utils import Logger
from com.articles.microapp.utils.constants import CommonConstants as consts

logger = Logger()


class ArticleDao(object):
    # 获取当前文件所在目录，然后拼接xml的文件名
    __XMLParser = XMLParser(os.path.dirname(os.path.realpath(__file__)) + '\\articles_dao.xml')
    __DbUtil = DbUtils.db_util()
    __cache = Cache()

    def get_banner(self, page=[consts.DEFAULT_PAGE_NO, consts.DEFAULT_PAGE_SIZE]):
        sql = self.__XMLParser.get_sql('queryBanner', page=page)
        return self.__DbUtil.selectall(sql)

    def get_articles(self, params={}, page=[consts.DEFAULT_PAGE_NO, consts.DEFAULT_PAGE_SIZE]):
        sql = self.__XMLParser.get_sql('queryArticle', params, page)
        results = self.__DbUtil.selectall(sql)
        articles = []
        for result in results:
            article = Article(**result)
            art_type = self.__cache.get_type(article.articleType)
            article.articleType = art_type.typeName
            tagstr = str(article.articleTags)
            tags = tagstr.split(',')
            tag_list = []
            for i in range(len(tags)):
                tag_obj = self.__cache.get_tag(tags[i])
                tag_list.append(tag_obj.tagName)
            article.articleTags = tag_list
            user = self.__cache.get_user(article.author)
            article.author = user.username
            # 点赞数
            article.likeCnt = self.get_like_count(article.articleId)
            # 评论数
            article.commentCnt = self.get_comment_cnt(article.articleId)
            articles.append(article.__dict__)
        qry_count = self.__XMLParser.get_sql('queryArticleCount', params)
        total = self.__DbUtil.selectone(qry_count)['total']
        return {
            "list": articles,
            "total": total
        }

    def get_article(self, article_id):
        sql = self.__XMLParser.get_sql('queryArticle', {'articleId': article_id})
        result = self.__DbUtil.selectone(sql)
        article = Article(**result)
        article.article_type = self.__cache.get_type(article.articleType).typeName
        tag_list = []
        for tag in str(article.articleTags).split(','):
            tag_list.append(self.__cache.get_tag(tag).tagName)
        article.articleTags = tag_list
        # 设置作者名
        article.author = self.__cache.get_user(article.author).__dict__
        # 设置点赞数
        article.likeCnt = self.get_like_count(article.articleId)
        # 设置评论数
        article.commentCnt = self.get_comment_cnt(article.articleId)
        return article

    def get_like_count(self, article_id):
        try:
            if String.is_empty(article_id):
                raise Exception('文章id不能为空！')
            sql = self.__XMLParser.get_sql('getLikeCnt')
            result = self.__DbUtil.selectone(sql, article_id)
            return result['likeCnt']
        except Exception as e:
            logger.error('获取文章点赞数失败！', e)
            return -1

    def get_comment_cnt(self, article_id):
        try:
            if String.is_empty(article_id):
                raise Exception('文章id不能为空！')
            sql = self.__XMLParser.get_sql('getRemarkCnt')
            result = self.__DbUtil.selectone(sql, article_id)
            return result['commentCnt']
        except Exception as e:
            logger.error('获取文章评论数失败！', e)
            return -1


if __name__ == '__main__':
    article = ArticleDao()
    print(article.get_articles())
    print(article.get_articles()['total'])
    # for art in article.get_articles():
    #     print(art.__dict__)
    # print({"list": article.get_articles(), "total": 5})
    # print(article.get_all())
    # cnt = article.get_article('b0eb662e-2532-11e9-ab14-d663bd873d93')
    # print(cnt)
    # print()
    # results = article.get_banner()
    # print(results)
